i'm trying to post js array of keys and values to php using axios and am really lost thanks for your help
here is the array i'm sending:
let arr = [];
arr["adID"] = uuidv4();
arr["price"] = price;
arr["city"] = city;
arr["street"] = street;
arr["rooms"] = rooms;
arr["building_number"] = building_number;
arr["entry"] = entry;
arr["apartment"] = apartment;
arr["user_id"] = 1;
sendDataFromJsToPhp("insertAd", arr);
here is the axios part:
sendDataFromJsToPhp(type, parametersArray) {
this.formData.append("data", "insertAd"); //type to create new ad is insertAd
this.formData.append(
"parameters",parametersArray); //type to create new ad is insertAd
axios({
method: "post",
url: this.url,
data: this.formData,
config: { headers: { "Content-Type": "multipart/form-data" } },
}).then(
(response) => {
console.log(response.data);
this.resultFromServer = response.data;
},
(error) => {
console.log(error);
}
);
//this is a work around that will get us array of keys and one of values and will merge them
//to get aray that represent the data we got
return this.resultFromServer;
}
here is the php:
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: *");
header("Access-Control-Allow-Methods: *");
header('Content-Type: application/json');
$DATA_RAW = file_get_contents("php://input");
$DATA_OBJ = json_decode($DATA_RAW);
$error = "";
if(isset($_POST)&&isset($_POST['data']))
$dataType = $_POST["data"];
if(isset($_POST)&&isset($_POST['parameters']))
$parameters=$_POST['parameters'];
print_r($parameters);
the errors present when i address the $parameters i get these errors: 1)Warning: Uninitialized string offset 0 in 2)b>Fatal error: Uncaught TypeError: Cannot access offset of type string on string in
thank you very much
If your array uses a string key value, instead of an int, stringify ignores that value.
Hence you have to create an object instead of array.
ie;
let arr = {};
arr.adID = uuidv4();
arr.price = price;
arr.city = city;
arr.street = street;
arr.rooms = rooms;
arr.building_number = building_number;
arr.entry = entry;
arr.apartment = apartment;
arr.user_id = 1;
sendDataFromJsToPhp("insertAd", arr);
And in the formData append;
this.formData.append(
"parameters", JSON.stringify(parametersArray)); //type to create new ad is insertAd